//
//  ONDayAheadViewController.m
//  Volatix
//
//  Created by Nguyen Minh Duc on 6/2/14.
//  Copyright (c) 2014 Familly. All rights reserved.
//

#import "ONDayAheadViewController.h"
#import "ONDayHeadSectionView.h"
#import "ONDayHeadTableViewCell.h"
#import "ONTabbarViewController.h"
#import "ONRealTimeSectionView.h"
#import "ONScrollViewCell.h"
#import "DSLCalendarView.h"
@interface ONDayAheadViewController ()<ONScrollViewCellDelegate,DSLCalendarViewDelegate,iCarouselDelegate,iCarouselDataSource,ONTabbarViewControllerDelegate>
{
    UITapGestureRecognizer *tapRec;
}
@property NSMutableArray *contents;

@property (weak, nonatomic) IBOutlet DSLCalendarView *DSLCalendar;
@end

@implementation ONDayAheadViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _dateSetting =[NSDate date];
    _iCountDate=0;
    _tempCurrentICarosel=0;
     _DSLCalendar.delegate = self;
    _currentVisible=0;
    [self initBaseColumnData];
    [self startPullDownRefresh];
    [self initICarosel];
    [self requestLoadByTime:[self getDateByNSDate:[NSDate date]]];

    
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.title = @"DAY AHEAD";
    /// change left Button
    ONTabbarViewController *_tabbar =(ONTabbarViewController*)self.tabBarController;
    _tabbar.tabbarDelegateDayAhead_Detail=self;
    _tabbar.isLeftBackButton = YES;
    [_tabbar.buttonSetting setHidden:true];
    // _tabbar.itemTabbarLeft.image=[UIImage imageNamed:@"arrow_left.png"];
    [_tabbar.ButtonLeft setImage:[UIImage imageNamed:@"arrow_left.png"] forState:UIControlStateNormal];
    
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    ONTabbarViewController *_tabbar =(ONTabbarViewController*)self.tabBarController;
    //_tabbar.itemTabbarLeft.image=[UIImage imageNamed:@"btn_add.png"];
    [_tabbar.ButtonLeft setImage:[UIImage imageNamed:@"btn_add.png"] forState:UIControlStateNormal];
    _tabbar.isLeftBackButton = NO;
    [_tabbar.buttonSetting setHidden:false];
    _tabbar.tabbarDelegateDayAhead_Detail=nil;
    
}

#pragma  mark - Support Function
-(NSString *)getDateByNSDate:(NSDate *)currDate
{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:currDate];
    //NSLog(@"%@",dateString);
    //dateString=[dateString stringByReplacingOccurrencesOfString:@" " withString:@"%"];
    // NSLog(@"Current %@",dateString);
    return dateString;
   
}
-(void)settingDateWith:(NSDate *)_date
{
    /// setting for today selection
    NSDateComponents *today = [_date dslCalendarView_dayWithCalendar:_DSLCalendar.visibleMonth.calendar];
    [_DSLCalendar setSelectedRange:[[DSLCalendarRange alloc] initWithStartDay:today endDay:today]];
}

-(NSString *)getDaySetting:(int)iNextDay andIsNeedGetNumberDay:(int)value
{
    NSDate *date= [self getForDays:iNextDay];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:(value==0)?@"dd":(value==1)?@"dd/MM/YYYY":@"YYYY-MM-dd HH:mm:ss"];
    NSString *currentLocalDate = [dateFormatter stringFromDate:date];
    //NSLog(@"currentLocalDate %@",currentLocalDate);
    return currentLocalDate;
}

- (NSDate *)getForDays:(int)days
{
    NSDateComponents *components= [[NSDateComponents alloc] init];
    [components setDay:days];/*setMonth:days];*///
    NSCalendar *calendar = [NSCalendar currentCalendar];
    return [calendar dateByAddingComponents:components toDate:(_dateSetting==nil)?[NSDate date]:[self getDateSettingTimer] options:0];
}
-(NSDate *)getDateSettingTimer
{
     NSDate *date = [NSDate date];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
    NSDateComponents *components_currentTime = [gregorian components: NSUIntegerMax fromDate: date];
    NSDateComponents *components_dataSetting = [gregorian components: NSUIntegerMax fromDate: _dateSetting];
    [components_dataSetting setHour:components_currentTime.hour];
    [components_dataSetting setMinute: components_currentTime.minute];
    [components_dataSetting setSecond: components_currentTime.second];
    
    NSDate *newDate = [gregorian dateFromComponents: components_dataSetting];
    return newDate;
}





-(void)initBaseColumnData
{
    self.columnArray = [[NSMutableArray alloc]init];
    for (int i=0; i<4; i++)
    {
        ONColumnTitleObject *column = [[ONColumnTitleObject alloc]init];
        column.allowToSelect = NO;
        column.mainColumn=1;
        switch (i) {
            case 0:
                column.name = @"HE";
                break;
            case 1:
                column.name = @"Price";
                break;
            case 2:
                column.name = @"Loss";
                break;
            case 3:
                column.name = @"Congestion";
                break;
            default:
                break;
        }
        [self.columnArray addObject:column];
        
    }
    
    ////dynamic column
    NSMutableArray * NSColumn=[APP_DELEGATE getingListDynamicColumnNameRealTime:false];
    _columnDynamic=[NSMutableArray arrayWithArray:NSColumn];
    int iDynamicColumn =[NSColumn count];
    for (int index=0; index<iDynamicColumn; index++)
    {
        ONColumnTitleObject  *item =[NSColumn objectAtIndex:index];
        [self.columnArray addObject:item];
        
    }
    int kColumnOnRealTime =3+iDynamicColumn;
    kNumberOfColumnOnRealTime=kColumnOnRealTime;
    /// update UI
    [self updateUIForViewWithColumn:kColumnOnRealTime];
    [self.tableView reloadData];

    
}
- (void)updateUIForViewWithColumn:(int) _nColumn{
    
    CGRect tableViewFrame = self.tableView.frame;
    CGRect pullDownViewFrame = self._refreshHeaderView.frame;
    
    // Update Tableview frame
    tableViewFrame.size.width = kWidthColumn * (_nColumn + 1);
    self.tableView.frame = tableViewFrame;
    
    // Update scrollView content size
    CGSize contentSize = self.tableView.contentSize;
    contentSize.height = 0;
    
    self.scrollView.contentSize =  contentSize;
    
    self._refreshHeaderView.frame = pullDownViewFrame;
}
-(void) initICarosel
{
    _contents= [[NSMutableArray alloc] init];
    [_contents addObject:@"1"];
    [_contents addObject:@"2"];
    [_contents addObject:@"3"];
    [_contents addObject:@"4"];
    [_contents addObject:@"5"];
    
    // _iCarousel.type = iCarouselTypeLinear;
    //if(_iCarousel!=nil)
    {
        [_iCarousel reloadData];
        /// scroll slow icarosel
        _iCarousel.scrollSpeed=0.1f;
    }
}




-(void)backToScreen:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    NSInteger numberOfCell = [self.dataUpdate count];
    return numberOfCell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 30;//44
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *reuseIdentifier = @"ONRealTimeTableViewCell";
    
    ONRealTimeTableViewCell *cell = (ONRealTimeTableViewCell*)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = (ONRealTimeTableViewCell *)[[[NSBundle mainBundle] loadNibNamed:reuseIdentifier owner:self options:nil] objectAtIndex:0];
    }
    
    ONObjectDayAhead *_obj = [self.dataUpdate objectAtIndex:indexPath.row];
    //_obj.dynamicColumnData=_columnDynamic;
    [cell loadCellData_DayAheadDetail:self.currentISOObject WithDataUpdate:_obj andNumberColumn:kNumberOfColumnOnRealTime andShowArrow:NO];
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 45;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *sectionView = [[UIView alloc]init];
    sectionView.backgroundColor = [UIColor clearColor];
    
    CGFloat currentX = 0;
    for (int i=0; i<[self.columnArray count]; i++) {
        
        
        ONRealTimeSectionView *view = [[ONRealTimeSectionView alloc]initWithFrame:CGRectMake(0, 0, kWidthColumn, kHeightSection)];
        ONColumnTitleObject *column =[self.columnArray objectAtIndex:i];
        //NSLog(@"column.name  %@",column.name);
        view.titleLabel.text = column.name;
        
        currentX = i*kWidthColumn;
        
        view.frame = CGRectMake(currentX, 0, kWidthColumn, kHeightSection);
        view.backgroundColor = [UIColor clearColor];
        sectionView.frame = CGRectMake(0, 0, currentX + kWidthColumn, kHeightSection);
        
        [sectionView addSubview:view];
    }
    
    return sectionView;
}



#pragma mark - UITableViewDelegate Methods

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // Deselect the row
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}




#pragma mark -
#pragma mark iCarousel methods

- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
    
    //NSLog(@"_contents %d",[_contents count]);
    return [_contents count];
}

- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
    
    //create new view if no view is available for recycling
    if (view == nil)
    {
        view=[[ONScrollViewCell alloc] initWithFrame:CGRectMake(0, 0, 320.0f, 57.0f)];
       
        //[view addSubview:scrollViewCell];
    }
    ONScrollViewCell *_iView =(ONScrollViewCell *)view;
    _iView.delegate=self;
     [_iView setInforDate:[self getDaySetting:_iCountDate andIsNeedGetNumberDay:1]];
     [_iView setInforLableButton:[self getDaySetting:_iCountDate andIsNeedGetNumberDay:0]];
    [_iView setInforCalendar:_currentISOObject.name];
    [_iView setAllVisible:(index==_currentVisible)?NO:YES];//setHidden:(index==_currentVisible)?NO:YES];
    
    return view;
}
- (UIView *)carousel:(iCarousel *)carousel placeholderViewAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
    if (view == nil)
    {
        view=[[ONScrollViewCell alloc] initWithFrame:CGRectMake(0, 0, 320.0f, 57.0f)];
        //[view addSubview:scrollViewCell];
    }
    ONScrollViewCell *_iView =(ONScrollViewCell *)view;
    _iView.delegate=self;
    [_iView setInforDate:[self getDaySetting:_iCountDate andIsNeedGetNumberDay:1]];
    [_iView setInforLableButton:[self getDaySetting:_iCountDate andIsNeedGetNumberDay:0]];
    [_iView setInforCalendar:_currentISOObject.name];
    
    return view;
}
- (CATransform3D)carousel:(iCarousel *)_carousel itemTransformForOffset:(CGFloat)offset baseTransform:(CATransform3D)transform
{
    //implement 'flip3D' style carousel
    transform = CATransform3DRotate(transform, M_PI / 8.0f, 0.0f, 1.0f, 0.0f);
    return CATransform3DTranslate(transform, 0.0f, 0.0f, offset * _iCarousel.itemWidth);
}

- (CGFloat)carousel:(iCarousel *)carousel valueForOption:(iCarouselOption)option withDefault:(CGFloat)value
{
    switch (option)
    {
        case iCarouselOptionWrap:
        {
            return YES;
        }
        case iCarouselOptionSpacing:
        {
            return value ;//1.1f;
        }
        default:
        {
            return value;
        }
    }
}

- (void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index
{
    //NSNumber *item = (self.items)[index];
    //NSLog(@"Tapped view number: ");
}
-(void)carouselDidEndDragging:(iCarousel *)carousel willDecelerate:(BOOL)decelerate
{
   
    NSLog(@"Request when finish");
    //[self requestLoadByTime:[self getDateByNSDate:[self getForDays:_iCountDate]]];
    
}
-(void)carouselCurrentItemIndexDidChange:(iCarousel *)carousel
{
    NSInteger getTemp=carousel.currentItemIndex;
    _currentVisible =carousel.currentItemIndex;
   // NSLog(@"Current ItemIndex %ld   ---------- %ld ",getTemp,_tempCurrentICarosel);
    
    if(_tempCurrentICarosel==4&&getTemp==0)
    {
     //   NSLog(@"Move Next");
        _iCountDate++;
    }
    else if(_tempCurrentICarosel==0&&getTemp==4)
    {
       // NSLog(@"+++++++++Move Back");
        _iCountDate--;
    }
    else if(_tempCurrentICarosel<=getTemp)
    {
       // NSLog(@"Move Next");
        _iCountDate++;
    }
    else{
       // NSLog(@"+++++++++Move Back");
        _iCountDate--;
    }
    
    
//    for (UIView *view in  _iCarousel.visibleItemViews) {
//        [view setHidden:true];
//    }
   // [_iCarousel.currentItemView setHidden:false];
    [_iCarousel reloadData];
     _tempCurrentICarosel=getTemp;
}
-(void)OnClickCalendar:(id)sender
{
    
    [self  settingDateWith:[self getForDays:_iCountDate]];
    [self setVisibleCalendar:true];
    
}
- (void)setVisibleCalendar:(BOOL)value
{
     [_DSLCalendar setHidden:!value];
    if(tapRec==nil)
    {
        tapRec = [[UITapGestureRecognizer alloc]
                  initWithTarget:self action:@selector(tap:)];
    }
    
    if(value)
    {
        self.scrollView.scrollEnabled=NO;
        self.tableView.scrollEnabled =NO;
        [self.tableView addGestureRecognizer: tapRec];
    }
    else
    {
        /// reload update data
        [self requestLoadByTime:[self getDateByNSDate:[self getForDays:_iCountDate]]];
        self.scrollView.scrollEnabled=YES;
        self.tableView.scrollEnabled =YES;
        [self.tableView removeGestureRecognizer:tapRec];
    }
}
-(void)tap:(UITapGestureRecognizer *)tapRec{
    
    if(self.DSLCalendar.hidden){return;}
     [self setVisibleCalendar:false];
}

#pragma mark - DSLCalendarViewDelegate methods

- (void)calendarView:(DSLCalendarView *)calendarView didSelectRange:(DSLCalendarRange *)range {
    if (range != nil) {
       // NSLog( @"Selected %ld - %ld - %ld", range.startDay.day, range.startDay.month,range.startDay.year);
         //range.endDay.day, range.endDay.month
        NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        _dateSetting = [gregorian dateFromComponents:range.startDay];
        _iCountDate=0;
        [_iCarousel reloadData];
         NSLog( @"Selected %@", _dateSetting);
    }
    else {
        NSLog( @"No selection" );
    }
}

- (DSLCalendarRange*)calendarView:(DSLCalendarView *)calendarView didDragToDay:(NSDateComponents *)day selectingRange:(DSLCalendarRange *)range {
    
   // NSLog(@"dasdsads");
    
    if (YES) { // Only select a single day
        return [[DSLCalendarRange alloc] initWithStartDay:day endDay:day];
    }
//    else if (NO) { // Don't allow selections before today
//        NSDateComponents *today = [[NSDate date] dslCalendarView_dayWithCalendar:calendarView.visibleMonth.calendar];
//        
//        NSDateComponents *startDate = range.startDay;
//        NSDateComponents *endDate = range.endDay;
//        
//        if ([self day:startDate isBeforeDay:today] && [self day:endDate isBeforeDay:today]) {
//            return nil;
//        }
//        else {
//            if ([self day:startDate isBeforeDay:today]) {
//                startDate = [today copy];
//            }
//            if ([self day:endDate isBeforeDay:today]) {
//                endDate = [today copy];
//            }
//            
//            return [[DSLCalendarRange alloc] initWithStartDay:startDate endDay:endDate];
//        }
//    }
    
    return range;
}
- (void)calendarView:(DSLCalendarView *)calendarView willChangeToVisibleMonth:(NSDateComponents *)month duration:(NSTimeInterval)duration {
    NSLog(@"Will show %@ in %.3f seconds", month, duration);
}

- (void)calendarView:(DSLCalendarView *)calendarView didChangeToVisibleMonth:(NSDateComponents *)month {
    NSLog(@"Now showing %@", month);
}

- (BOOL)day:(NSDateComponents*)day1 isBeforeDay:(NSDateComponents*)day2 {
    return ([day1.date compare:day2.date] == NSOrderedAscending);
}








#pragma mark - Webservice Methods

// when pull down refresh, this method will be called
- (void)requestGetData {
    // hardcode
    [self requestLoadByTime:[self getDateByNSDate:[self getForDays:_iCountDate]]];
}
-(void)requestLoadByTime:(NSString *)date_time
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        [self loadDatahistoryOfSymbleWithTime:date_time];
        // perform main thread operation
        //        dispatch_sync(dispatch_get_main_queue(), ^{
        //
        //        });
    });
}
-(void)loadDatahistoryOfSymbleWithTime:(NSString *)date_time
{
    //[params setObject:[NSNumber numberWithInt:0]  forKey:@"PageIndex"];
    //[params setObject:[NSNumber numberWithInt:100] forKey:@"pageSize"];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:date_time  forKey:@"DATE_TIME"];//
    if(_currentISOObject.type==LEVEL_ISO)
    {
        //==> iso
        [params setObject:[NSNumber numberWithInt:LEVEL_ISO]  forKey:@"KIND"];
        [params setObject:_currentISOObject.name forKey:@"ISO"];
    }
    else if(_currentISOObject.type==LEVEL_LOADZONE)//if(_currentISOObject.iso!=nil&&_currentISOObject.loadZone==nil)
    {
        //==> loadzone
        [params setObject:[NSNumber numberWithInt:LEVEL_LOADZONE]  forKey:@"KIND"];
        [params setObject:_currentISOObject.iso forKey:@"ISO"];
        [params setObject:_currentISOObject.name forKey:@"LOADZONE"];
    }
    else if(_currentISOObject.type==LEVEL_POWERPOINT)//(_currentISOObject.iso!=nil&&_currentISOObject.loadZone!=nil)
    {
        /// ==> powerpoint
        [params setObject:[NSNumber numberWithInt:LEVEL_POWERPOINT]  forKey:@"KIND"];
        [params setObject:_currentISOObject.iso forKey:@"ISO"];
        [params setObject:_currentISOObject.loadZone forKey:@"LOADZONE"];
        [params setObject:_currentISOObject.name forKey:@"POWERPOINT"];
    }
    else
    {
        NSLog(@"*********** DONT KNOW *****");
        return;
    }

    [[WebserviceManager sharedInstance] operationWithType:ENUM_API_REQUEST_GET_HISTORY andPostMethodKind:enumAPIRequestMethod_GET andParams:params andString:nil inView:self.view completeBlock:^(id responseObject) {
        if(self.dataUpdate==nil)
        {
            self.dataUpdate= [[NSMutableArray alloc] init];
        }
        else
        {
            [self.dataUpdate removeAllObjects];
        }
        //if(responseObject==nil||[responseObject count]==0){return ;}
        for(NSDictionary *item in responseObject ) {
            
            ONObjectDayAhead *_obj=[ONObjectDayAhead modelObjectWithDictionary:item];
            if(_obj!=nil)
            {
                //NSLog(@"HE %8.3f",_obj.hourending);
                [self.dataUpdate addObject:_obj];
            }
            
        }
        
        [self.tableView reloadData];
        [self doneLoadingTableViewData];
    } failureBlock:^(NSError *error) {
        //
         [self doneLoadingTableViewData];
    }];
    
    
   // [self doneLoadingTableViewData];
}



-(void)dealloc
{
    self.DSLCalendar.delegate=nil;
    _iCarousel.delegate=nil;
    _iCarousel.dataSource=nil;
    ONTabbarViewController *_tabbar =(ONTabbarViewController*)self.tabBarController;
    _tabbar.tabbarDelegateDayAhead_Detail=nil;
}
@end


